<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="24">
              <a-form-item label="开课学年">
                <a-select
                  show-search
                  allowClear
                  placeholder="请选择开课学年"
                  @change="changeSchoolYear"
                  v-model="queryParam.schoolYearId">
                  <a-select-option v-for="item of this.schoolYearList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="开课学期">
                <a-select show-search allowClear placeholder="请选择开课学期" v-model="queryParam.termId">
                  <a-select-option v-for="item of this.schoolTermList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="开课课程">
                <a-select show-search allowClear placeholder="请选择开课课程" v-model="queryParam.courseId">
                  <a-select-option v-for="item of this.courseList" :key="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24">
              <a-form-item label="轮次">
                <a-select show-search allowClear placeholder="请选择轮次" v-model="queryParam.frequencyIndex">
                  <a-select-option v-for="item of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" :key="item">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="4" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table ref="table" :columns="columns" :data="loadData" :rowKey="(record) => record.courseSelectionId">
        <span slot="dayOfWeek" slot-scope="text, record">
          {{
            record.dayOfWeek
              .split(',')
              .map((item) => {
                return `周${item}`
              })
              .join('、')
          }}
        </span>
        <span slot="homeworkAttachmentName" slot-scope="text, record">
          <span v-if="record.homeworkAttachmentName">
            <a @click="sysFileInfoDownload(record.homeworkFileId)">{{ record.homeworkAttachmentName }}</a>
          </span>
          <a-upload
            v-else
            :customRequest="uploadHomeworkFile"
            :data="record"
            :multiple="true"
            :showUploadList="false"
            name="file"
          >
            <a-button size="small"><a-icon type="upload"/>上传</a-button>
          </a-upload>
        </span>
        <span slot="homeworkCorrectedAttachmentName" slot-scope="text, record">
          <span v-if="record.homeworkCorrectedAttachmentName">
            <a @click="sysFileInfoDownload(record.correctedHomeworkFileId)">
              {{ record.homeworkCorrectedAttachmentName }}
            </a>
          </span>
          <span v-else>-</span>
        </span>
        <span slot="operations" slot-scope="text, record">
          <a-popconfirm
            title="确认提交作业？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="confirmStuSubmit(record.homeworkId)">
            <a-button size="small" v-if="record.stuConfirmed === 0">提交作业</a-button>
          </a-popconfirm>
          <a-upload
            :customRequest="uploadHomeworkFile"
            :data="record"
            :multiple="true"
            :showUploadList="false"
            name="file"
          >
            <a-button size="small" v-if="record.stuConfirmed === 0">重新上传</a-button>
          </a-upload>
        </span>
      </s-table>
    </a-card>
  </div>
</template>
<script>
  import { STable, XDown } from '@/components'
  import { sysFileInfoDownload } from '@/api/modular/system/fileManage'
  import { homeworkPageForStudent, uploadHomeworkFile, stuConfirm } from '@/api/modular/main/courseHomeworkManage'
  import { sysSchoolYearList } from '@/api/modular/system/sysSchoolYearManage'
  import { sysSchoolTermList } from '@/api/modular/system/sysSchoolTermManage'
  import { courseList } from '@/api/modular/system/courseManage'

  const currentYear = new Date().getFullYear()
  // const currentMonth = new Date().getMonth() + 1

  export default {
    components: {
      STable,
      XDown
    },
    data() {
      return {
        // 查询参数
        queryParam: {
          schoolYearId: undefined,
          termId: undefined,
          courseId: undefined,
          frequencyIndex: undefined
        },
        courseList: [],
        schoolYearList: [],
        schoolTermList: [],
        // 表头
        columns: [
          {
            title: '开课课程',
            align: 'center',
            dataIndex: 'courseName'
          },
          {
            title: '实验项目',
            align: 'center',
            dataIndex: 'projectName'
          },
          {
            title: '轮次',
            align: 'center',
            width: '80px',
            dataIndex: 'frequencyIndex'
          },
          {
            title: '实验老师',
            align: 'center',
            ellipsis: true,
            dataIndex: 'teacherName'
          },
          {
            title: '开课时间',
            align: 'center',
            ellipsis: true,
            width: '100px',
            dataIndex: 'dayOfWeek',
            scopedSlots: { customRender: 'dayOfWeek' }
          },
          {
            title: '教室',
            align: 'center',
            ellipsis: true,
            dataIndex: 'classroomName'
          },
          {
            title: '上传作业时间',
            align: 'center',
            ellipsis: true,
            dataIndex: 'homeworkUploadDate'
          },
          {
            title: '作业',
            align: 'center',
            ellipsis: true,
            dataIndex: 'homeworkAttachmentName',
            scopedSlots: { customRender: 'homeworkAttachmentName' }
          },
          {
            title: '批改作业时间',
            align: 'center',
            ellipsis: true,
            dataIndex: 'homeworkCorrectedDate'
          },
          {
            title: '批改作业',
            align: 'center',
            ellipsis: true,
            dataIndex: 'homeworkCorrectedAttachmentName',
            scopedSlots: { customRender: 'homeworkCorrectedAttachmentName' }
          },
          {
            title: '操作',
            align: 'center',
            width: '180px',
            dataIndex: 'operations',
            scopedSlots: { customRender: 'operations' }
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          return homeworkPageForStudent(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        allowedFileTypes: [
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-powerpoint',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'application/pdf'
        ]
      }
    },
    created() {
      this.getSchoolYearList()
      this.getCourseList()
    },
    methods: {
      /**
       * load学年列表
       */
      getSchoolYearList() {
        sysSchoolYearList().then((res) => {
          if (res.success) {
            this.schoolYearList = res.data
            const d = res.data.find(item => parseInt(item.startDate.substr(0, 4)) === currentYear)
            if (d) {
              this.queryParam.schoolYearId = d.id
              this.getSchoolTermList(d.id)
            }
          }
        })
      },
      /**
       * load开课学期
       */
      getSchoolTermList(schoolYearId) {
        sysSchoolTermList({
          schoolYearId: schoolYearId
        }).then((res) => {
          if (res.success) {
            this.schoolTermList = res.data
            const d = res.data.find(item => {
              // console.log('new Date()=', new Date(), 'item.startDate=', item.startDate, 'item.endDate=', item.endDate)
              if (new Date(item.startDate) <= new Date() && new Date() <= new Date(item.endDate)) {
                return item
              }
            })
            if (d) this.queryParam.termId = d.id
            this.$refs.table.refresh()
          }
        })
      },
      /**
       * load课程
       */
      getCourseList() {
        courseList().then((res) => {
          if (res.success) {
            this.courseList = res.data
          }
        })
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      uploadHomeworkFile(data) {
        this.$loading.show()
        const file = data.file
        const fileSize = file.size
        const fileType = file.type
        if (this.allowedFileTypes.indexOf(fileType) === -1) {
          this.$message.error('请上传word,ppt,pdf文件')
          this.$loading.hide()
          return
        }
        if (fileSize / 1024 / 1024 > 50) {
          this.$message.error('上传文件大小不能超过50M')
          this.$loading.hide()
          return
        }

        const formData = new FormData()
        formData.append('file', file)
        formData.append('courseSelectionId', data.data.courseSelectionId)
        uploadHomeworkFile(formData).then((res) => {
          if (res.success) {
            this.$message.success('上传成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('上传失败：' + res.message)
          }
        }).catch(() => {
          this.$loading.hide()
        }).finally(() => {
          this.$loading.hide()
        })
      },
      /**
       * 下载文件（所有文件）
       */
      sysFileInfoDownload(fileId) {
        this.$loading.show()
        sysFileInfoDownload({ id: fileId })
          .then((res) => {
            this.$loading.hide()
            this.downloadfile(res)
          })
          .catch(() => {
            this.$loading.hide()
            this.$message.error('下载错误：获取文件流错误')
          }).finally(() => {
            this.$loading.hide()
        })
      },
      downloadfile(res) {
        var blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
        var contentDisposition = res.headers['content-disposition']
        var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        var result = patt.exec(contentDisposition)
        var filename = result[1]
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob) // 创建下载的链接
        var reg = /^["](.*)["]$/g
        downloadElement.style.display = 'none'
        downloadElement.href = href
        downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
      },
      changeSchoolYear(schoolYearId) {
        this.queryParam.termId = undefined
        this.getSchoolTermList(schoolYearId)
      },
      confirmStuSubmit(id) {
        stuConfirm(id).then(res => {
          if (res.success) {
            this.$refs.table.refresh()
          }
        })
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }

  button {
    margin-right: 8px;
  }
</style>
